package com.study.base.io.nio.multiselector;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by tan on 2017/7/19.
 */
public class Reactor implements Runnable {
	private Selector selector;

	private ServerSocketChannel serverSocket;

	public Reactor(Selector selector, ServerSocketChannel serverSocket) {
		this.selector = selector;
		this.serverSocket = serverSocket;
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				selector.select();
				Set<SelectionKey> keySet = selector.selectedKeys();
				Iterator it = keySet.iterator();
				while (it.hasNext()) {
					//当key.isAcceptable()==true时，key是serverSocket的key
					//当key.isReadable()==true时，key是客户端的key
					SelectionKey key = (SelectionKey) it.next();
					System.out.println("has  " + key.isAcceptable() + "   " + Thread.currentThread().getId());
					//dispatch(key);
					//selector.wakeup();

					it.remove();

					//四个线程 都会收到SelectKey
					//但是其中三个线程 serverSocket.accept()获得的socket是null
					SocketChannel socket = serverSocket.accept();
					if (socket == null) {
						System.out.println("socket  null");
					}
				}

				keySet.clear();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void dispatch(SelectionKey key) {

		Runnable r = (Runnable) (key.attachment());
		if (r != null) {
			r.run();
		}
	}
}